from fastapi import APIRouter, Request, HTTPException
from typing import Optional

from service.instagram_downloader_service import InstagramDownloaderService
from mrouter.domain.WxCloudRunHeader import WxCloudRunHeader
from utils.response import create_response
from config.logging_config import ProjectLoggers
from dto.instagram_request import (
    InstagramInfoRequest, InstagramUrlRequest, InstagramMultiQualityRequest, 
    InstagramUserMediaRequest
)
from dto.instagram_response import (
    InstagramInfoResponse, InstagramDownloadUrlResponse, InstagramMultiQualityResponse,
    InstagramUserMediaResponse, InstagramSupportedQualitiesResponse, InstagramUrlTypesResponse
)

logger = ProjectLoggers.get_service_logger()
router = APIRouter(prefix="/instagram", tags=["Instagram视频下载"])

# 创建服务实例
instagram_service = InstagramDownloaderService()

@router.post("/info", response_model=InstagramInfoResponse)
async def get_instagram_media_info(
    request: Request,
    info_request: InstagramInfoRequest
):
    """
    获取Instagram媒体信息
    
    - **instagram_url**: Instagram链接（Reel、帖子、IGTV、Stories）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取Instagram媒体信息: {info_request.instagram_url}")
        
        # 调用服务获取媒体信息
        result = await instagram_service.get_media_info(info_request.instagram_url)
        
        if result["success"]:
            logger.info(f"成功获取Instagram媒体信息: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取媒体信息",
                data=result["data"]
            )
        else:
            logger.warning(f"获取Instagram媒体信息失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"Instagram媒体信息请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取Instagram媒体信息接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/download-url", response_model=InstagramDownloadUrlResponse)
async def get_instagram_download_url(
    request: Request,
    url_request: InstagramUrlRequest
):
    """
    获取Instagram媒体直接下载链接
    
    - **instagram_url**: Instagram链接
    - **quality**: 视频质量（360p, 480p, 720p, 1080p, best, worst）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取Instagram下载链接: {url_request.instagram_url}, 质量: {url_request.quality}")
        
        # 调用服务获取下载链接
        result = await instagram_service.get_download_urls(
            instagram_url=url_request.instagram_url,
            quality=url_request.quality
        )
        
        if result["success"]:
            logger.info(f"成功获取Instagram下载链接: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取下载链接",
                data=result["data"]
            )
        else:
            logger.warning(f"获取Instagram下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"Instagram下载链接请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取Instagram下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/multi-quality-urls", response_model=InstagramMultiQualityResponse)
async def get_instagram_multi_quality_urls(
    request: Request,
    multi_request: InstagramMultiQualityRequest
):
    """
    获取Instagram媒体多种质量的下载链接
    
    - **instagram_url**: Instagram链接
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取Instagram多质量下载链接: {multi_request.instagram_url}")
        
        # 调用服务获取多质量下载链接
        result = await instagram_service.get_multiple_quality_urls(multi_request.instagram_url)
        
        if result["success"]:
            logger.info(f"成功获取Instagram多质量下载链接: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取多质量下载链接",
                data=result["data"]
            )
        else:
            logger.warning(f"获取Instagram多质量下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"Instagram多质量下载链接请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取Instagram多质量下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/user-media", response_model=InstagramUserMediaResponse)
async def get_user_media(
    request: Request,
    user_request: InstagramUserMediaRequest
):
    """
    获取Instagram用户最新媒体列表
    
    - **username**: Instagram用户名
    - **count**: 获取数量（1-50，默认12）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取Instagram用户媒体: {user_request.username}, 数量: {user_request.count}")
        
        # 调用服务获取用户媒体
        result = await instagram_service.get_user_media_urls(
            username=user_request.username,
            count=user_request.count
        )
        
        if result["success"]:
            logger.info(f"成功获取用户 {user_request.username} 的媒体列表")
            return create_response(
                code=200,
                msg="成功获取用户媒体列表",
                data=result["data"]
            )
        else:
            logger.warning(f"获取用户媒体列表失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"用户媒体请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取用户媒体接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/qualities", response_model=InstagramSupportedQualitiesResponse)
async def get_supported_qualities():
    """
    获取支持的视频质量选项
    """
    try:
        qualities = ["360p", "480p", "720p", "1080p", "best", "worst"]
        
        result = {
            "qualities": qualities,
            "default_quality": "best",
            "description": "360p-1080p为固定分辨率，best为最佳质量，worst为最低质量。Instagram媒体质量取决于原内容。"
        }
        
        return create_response(
            code=200,
            msg="获取支持的质量选项成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取支持质量选项接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/url-types", response_model=InstagramUrlTypesResponse)
async def get_supported_url_types():
    """
    获取支持的Instagram URL类型
    """
    try:
        url_types = [
            {
                "type": "Instagram Posts",
                "pattern": "/p/POST_ID/",
                "description": "普通Instagram帖子"
            },
            {
                "type": "Instagram Reels",
                "pattern": "/reel/REEL_ID/",
                "description": "Instagram短视频Reels"
            },
            {
                "type": "Instagram TV",
                "pattern": "/tv/TV_ID/",
                "description": "Instagram长视频IGTV"
            },
            {
                "type": "Instagram Stories",
                "pattern": "/stories/username/STORY_ID/",
                "description": "Instagram故事（需要及时访问）"
            }
        ]
        
        examples = {
            "post": "https://www.instagram.com/p/ABC123/",
            "reel": "https://www.instagram.com/reel/DKv_9G6RR2K/",
            "tv": "https://www.instagram.com/tv/XYZ789/",
            "story": "https://www.instagram.com/stories/username/123456/"
        }
        
        result = {
            "url_types": url_types,
            "examples": examples,
            "description": "支持多种Instagram媒体URL格式，包括普通帖子、Reels、IGTV和Stories"
        }
        
        return create_response(
            code=200,
            msg="获取支持的URL类型成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取支持URL类型接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/quick-url")
async def quick_get_instagram_url(
    request: Request,
    instagram_url: str,
    quality: Optional[str] = "best"
):
    """
    快速获取Instagram媒体下载链接（简化接口）
    
    - **instagram_url**: Instagram链接
    - **quality**: 视频质量，默认best
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 快速获取Instagram下载链接: {instagram_url}")
        
        # 验证Instagram URL
        if not instagram_url:
            return create_response(code=400, msg="Instagram链接不能为空")
        
        # 简单验证Instagram链接
        valid_domains = ['instagram.com', 'www.instagram.com', 'm.instagram.com']
        if not any(domain in instagram_url for domain in valid_domains):
            return create_response(code=400, msg="请提供有效的Instagram链接")
        
        # 检查是否包含媒体相关路径
        media_patterns = ['/p/', '/reel/', '/tv/', '/stories/']
        if not any(pattern in instagram_url for pattern in media_patterns):
            return create_response(code=400, msg="链接必须包含媒体内容")
        
        # 调用服务获取下载链接
        result = await instagram_service.get_download_urls(
            instagram_url=instagram_url,
            quality=quality or "best"
        )
        
        if result["success"]:
            data = result["data"]
            response_data = {
                "title": data["title"],
                "download_url": data["download_url"],
                "uploader": data.get("uploader"),
                "format": data["format"],
                "resolution": data["resolution"],
                "duration": data.get("duration"),
                "thumbnail": data.get("thumbnail"),
                "like_count": data.get("like_count"),
                "view_count": data.get("view_count"),
                "is_video": data["is_video"]
            }
            
            logger.info(f"快速获取Instagram下载链接成功: {data['title']}")
            return create_response(
                code=200,
                msg="成功获取下载链接",
                data=response_data
            )
        else:
            logger.warning(f"快速获取Instagram下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except Exception as e:
        logger.error(f"快速获取Instagram下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}") 